package com.baizhi.controller;

import com.baizhi.entity.Address;
import com.baizhi.entity.Result;
import com.baizhi.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @RequestMapping("findAll")
    @ResponseBody
    public List<Address> findAll(){
        return addressService.findAll();
    }

    @RequestMapping("findById")
    @ResponseBody
    public Address findById(String id){
        return addressService.findById(id);
    }

    @RequestMapping("findByUserId")
    @ResponseBody
    public List<Address> findByUserId(String userId){
        List<Address> byUserId = addressService.findByUserId(userId);
        return byUserId;
    }

    @RequestMapping("save")
    public Result save(Address address){
        Result result = null;
        try{
            addressService.save(address);
        }catch (Exception e){
            e.printStackTrace();
            result = new Result();
            result.setMessage("添加失败");
            throw new RuntimeException("添加失败");
        }
        return result;
    }

    @RequestMapping("update")
    @ResponseBody
    public Result update(Address address){
        Result result = null;
        try{
            addressService.update(address);
        }catch (Exception e){
            e.printStackTrace();
            result = new Result();
            result.setMessage("更新失败");
            throw new RuntimeException("更新失败");
        }
        return  result;
    }

    @RequestMapping("delete")
    @ResponseBody
    public Result delete(String id){
        Result result = null;
        try{
            addressService.delete(id);
            result = new Result();
            result.setMessage("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            result = new Result();
            result.setMessage("删除失败啊");
        }
        return result;
    }
}
